//路由拦截器
//需要登录的界面
let needLoginRouter = [
  "/cart",
  "/user", //包含user的界面
];
let notNeedLoginRouter = [
  "/user/cart",
  "/user/order/checkorder",
  "/user/address/editaddress",
  "/user/order/payConfirm"
];
export default ({
  app,
  store
}) => {
  app.router.beforeEach((to, from, next) => {
    let boolLogin = false; //当前用户登陆控制参数，true表示未登录
    let boolNeed = false; //当前路由否在需要登陆列表中
    let boolNotNeed = false;
    let userInfo = null;
    try {
      userInfo = JSON.parse(localStorage.getItem("userInfo"));
    } catch (e) {
      userInfo = localStorage.getItem("userInfo");
    }
    let offsetIndex=to.fullPath.indexOf('offset');
    let fullPath="";
    if(offsetIndex!=-1){
      fullPath=to.fullPath.substring(0,offsetIndex-1);
    }
    else{
      fullPath=to.fullPath;
    }
    store.commit('over/setBasicUrl', fullPath); //保存路由信息
    store.commit('user/setUserInfo', userInfo); //保存登陆信息
    //更改登陆状态：未登录
    if (userInfo == "" || userInfo == undefined || userInfo == null || userInfo == {}) {
      boolLogin = true; //需要登录
      store.commit('user/setIsLogin', false); //更改登陆状态：未登录
    } else {
      boolLogin = false; //不需要登录
      store.commit('user/setIsLogin', true); //更改登陆状态：已登录
    }
    //*******判断是否在需要登陆的特定列表中*******//     
    for (let i = 0; i < needLoginRouter.length; i++) {
      if (to.fullPath.indexOf(needLoginRouter[i]) != -1) {
        boolNeed = true;
      }
    }
    //*******判断是否在不需要登陆的特定列表中*******//     
    for (let i = 0; i < notNeedLoginRouter.length; i++) {
      if (to.fullPath.indexOf(notNeedLoginRouter[i]) != -1) {
        boolNotNeed = true;
      }
    }
    if (boolNeed && boolLogin && !boolNotNeed) {
      next({
        path: "/login",
        query: {
          redirect: to.fullPath,
        }
      });
    } else {
      next();
    }
  })
}
